package com.scisoft.scan.control.stock;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.scisoft.scan.control.ClearEditText;
import com.scisoft.scan.control.CommonAdapter;
import com.scisoft.scan.control.CommonViewHolder;
import com.scisoft.scan.control.MainMenuActivity;
import com.scisoft.scan.control.ScanHelper;
import com.scisoft.scan.data.BarCodeBean;
import com.scisoft.scan.data.QueryPageBean;
import com.scisoft.scan.data.stock.EasyPartBean;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.ws.WebServiceHelper;
import com.scisoft.scan.ws.WebServiceHelper_Stock;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import static com.scisoft.scan.control.CommonAdapter.LOADING_END;
import static com.scisoft.scan.control.CommonAdapter.LOADING_MORE;
import static com.scisoft.scan.control.CommonAdapter.PULLUP_LOAD_MORE;

public class EasyPartActivity extends Activity {
    private ImageView iv_Back; //返回按钮
    private ImageView iv_query; //搜索按钮
    private ClearEditText et_bar;//搜索框
    //分页配置表
    private QueryPageBean pageBean = null;
    private int currentPage = 0;
    //分页显示控件
    private SwipeRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    private EasyPartAdapter easyPartAdapter;
    private LinearLayoutManager mLayoutManager;
    private int lastVisibleItem; //最后一个可见Item的位置，关键所在
    float lastY = 0;

    @Override
    @SuppressLint("ClickableViewAccessibility")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_part);
        //初始化扫码
        init();
        //返回
        iv_Back = findViewById(R.id.iv_back);
        iv_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(EasyPartActivity.this, MainMenuActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent);
                finish();
            }
        });
        et_bar = findViewById(R.id.et_bar);
        //搜索框
        iv_query = findViewById(R.id.iv_query);
        iv_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QueryData(true);
            }
        });
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int fullWidth = displayMetrics.widthPixels;


        mRefreshLayout = findViewById(R.id.swipe_layout);
        //mRefreshLayout.setEnabled(false);
        mRefreshLayout.setProgressViewEndTarget(true, 0);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mRefreshLayout.setRefreshing(false);
                QueryData(true);
            }
        });
        mRecyclerView = findViewById(R.id.lv_data);
        easyPartAdapter = new EasyPartAdapter(EasyPartActivity.this);
        easyPartAdapter.setItemLayout(R.layout.item_easypart, R.id.hsv, R.id.layout_show, R.id.layout_hide, fullWidth);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        easyPartAdapter.setOnItemClickListener(new EasyPartAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                EasyPartBean easyPartBean = easyPartAdapter.getItemData(position);
                if (easyPartBean != null) {
                    Intent intent = new Intent(EasyPartActivity.this, EasyPartInfoActivity.class);
                    intent.putExtra("data", easyPartBean);
                    startActivity(intent);
                }
            }
        });
        //滚动的时候清空左滑按钮
        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        if (Math.abs(event.getY() - lastY) > 5)
                            easyPartAdapter.clearLeftMenuList();
                }
                return false;
            }
        });
        mRecyclerView.setAdapter(easyPartAdapter);
        //设置滑动监听
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //判断是否滑动到底
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == easyPartAdapter.getItemCount()) {
                    //滑动到底，需要改变状态为 上拉加载更多
                    easyPartAdapter.changeMoreStatus(LOADING_MORE);
                    QueryData(false);
                } else {
                    easyPartAdapter.changeMoreStatus(PULLUP_LOAD_MORE);
                }
            }

            //更新最后可见位置
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();

            }
        });
        QueryData(true);

    }

    //查询库存
    private void QueryData(boolean refresh) {
        CommonUtil.showPress(this);
        QueryTask queryTask = new QueryTask(EasyPartActivity.this, refresh);
        queryTask.execute();
    }

    //绑定数据
    private void BindData(Context context, List<EasyPartBean> newData, boolean refresh) {
        //清空
        easyPartAdapter.clearLeftMenuList();
        //数据
        if (!refresh) {
            if (newData.size() > 0) {
                easyPartAdapter.addMoreItem(newData);
            } else {
                easyPartAdapter.changeMoreStatus(LOADING_END);
            }
        } else {
            if (newData.size() > 0) {
                easyPartAdapter.clearAddItem(newData);
            } else {
                easyPartAdapter.clearAddItem(newData);
                easyPartAdapter.changeMoreStatus(LOADING_END);
            }
        }
    }

    //查询库存服务
    class QueryTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        boolean mrefresh = true;
        private List<EasyPartBean> newData = new ArrayList<>();

        QueryTask(Context context, boolean refresh) {
            super();
            mcontext = context;
            mrefresh = refresh;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                String condition = et_bar.getUpperText().toString();
                //重新刷新
                if (mrefresh) {
                    pageBean = null;
                }
                //第一次程序时需要先查询分页信息
                if (pageBean == null) {
                    pageBean = WebServiceHelper_Stock.STOCK_08(condition);
                    currentPage = 0;
                }
                //翻页
                currentPage++;
                //判断是否全部显示，如果没有就查询下一页
                if (currentPage <= pageBean.pageCount) {
                    newData = WebServiceHelper_Stock.STOCK_11(condition, pageBean.pageSize, currentPage);
                }
                //超过最大页则返回
                if (currentPage > pageBean.pageCount) {
                    currentPage = pageBean.pageCount;
                }
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext, newData, mrefresh);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }


    //以下为扫码相关
    //初始化
    private void init(){
        //初始化Profile
        ScanHelper.CreateProfile(this);
        //设置广播消息的接收器
        registerReceiver();
    }

    //查询条码服务
    class QueryBarCodeTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private String barCode;
        private BarCodeBean barCodeBean = null;

        QueryBarCodeTask(Context context, String barCode) {
            super();
            mcontext = context;
            this.barCode = barCode;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                barCodeBean = WebServiceHelper.ParseBarCode(barCode);
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                if (barCodeBean == null || barCodeBean.barType == BarCodeBean.BAR_UNKNOWN) {
                    Toast.makeText(EasyPartActivity.this, "无效二维码：" + barCode, Toast.LENGTH_LONG).show();
                } else if (barCodeBean.barType == BarCodeBean.BAR_PART) {
                    et_bar.setText(barCodeBean.partBean.partNo);
                    QueryData(true);
                } else {
                    Toast.makeText(EasyPartActivity.this, "请扫描配件", Toast.LENGTH_LONG).show();
                }
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //扫码处理
    private void ScanData(String barCode) throws Exception {
        if (barCode != null && barCode.length() > 0) {
            CommonUtil.showPress(this);
            QueryBarCodeTask queryBarCodeTask = new QueryBarCodeTask(EasyPartActivity.this, barCode);
            queryBarCodeTask.execute();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unRegisterReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();
    }

    //注册广播
    private void registerReceiver() {
        //IntentFilter intFilter = new IntentFilter(ScanManager.ACTION_SEND_SCAN_RESULT);
        //registerReceiver(mResultReceiver, intFilter);
        IntentFilter filter = new IntentFilter();
        filter.addAction(ScanHelper.ACTION_RESULT_NOTIFICATION);   // for notification result
        filter.addAction(ScanHelper.ACTION_RESULT);                // for error code result
        filter.addCategory(Intent.CATEGORY_DEFAULT);    // needed to get version info
        filter.addAction(ScanHelper.ACTION_SCAN_OUTPUT); // register to received broadcasts via DataWedge scanning
        registerReceiver(mResultReceiver, filter);
    }

    //取消注册广播
    private void unRegisterReceiver() {
        try {
            unregisterReceiver(mResultReceiver);
        } catch (Exception e) {
            Toast.makeText(this, "注销扫码失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    //监听扫码数据的广播，当设置广播输出时作用该方法获取扫码数据
    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ScanHelper.ACTION_SCAN_OUTPUT)) {
                // 处理扫码结果
                try {
                    String decodedData = intent.getStringExtra("com.symbol.datawedge.data_string");
                    ScanData(decodedData);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(EasyPartActivity.this, "扫描失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    };

    //适配器相关功能
    class EasyPartAdapter extends CommonAdapter<EasyPartBean> {
        //构造函数
        public EasyPartAdapter(Context context) {
            super(context);
        }

        @Override
        public void convert(CommonViewHolder holder, final EasyPartBean easyPartBean, int position) {
            TextView tv_partNo = holder.getView(R.id.tv_partNo);
            TextView tv_partName = holder.getView(R.id.tv_partName);
            TextView tv_supplierCount = holder.getView(R.id.tv_supplierCount);
            ImageView iv_img = holder.getView(R.id.iv_img);
            //获取相应索引的ItemBean对象
            EasyPartBean bean = mList.get(position);
            //设置控件的对应属性值
            tv_partNo.setText(bean.partCode);
            tv_partName.setText(bean.partName);
            tv_supplierCount.setText("供应商数量：" + bean.supplierCount);
            if (bean.imgUrl != null && !bean.imgUrl.equals("")) {
                Picasso.with(mContext).load(bean.imgUrl).into(iv_img);
            } else {
                iv_img.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_noimage));
            }
        }

    }

}
